package informationplatform.overtime

import informationplatform.UserGroup;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import  groovy.util.Eval;

import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.List;
class StasticOvertimeController {
	def sf= new SimpleDateFormat("yyyy-MM-dd")
	def sftime= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
	def overtimeService

	def list() {
	}

	def search() {

		//查出结果集
		def overtimeList = Overtime.withCriteria {
			isNotNull('punchEndClockTime')

			// > '从日期'
			if(StringUtils.isNotBlank(params.qStartTime)){
				ge('punchStartClockTime',sf.parse(params.qStartTime))
			}

			// < '到日期' + 1
			if(StringUtils.isNotBlank(params.qEndTime)){
				Calendar cal = Calendar.getInstance();
				cal.setTime(sf.parse(params.qEndTime));
				cal.add(Calendar.DAY_OF_YEAR, 1)

				lt('punchStartClockTime',cal.getTime())
			}

			if(StringUtils.isNotBlank(params.userGroup)){
				applicant{
					group{
						eq('name', params.userGroup)
					}
				}
			}

			//-------------------------------------排序 START
			def sortIndex=0
			def sortStr
			def feildStr
			while(params."sort[${sortIndex}][dir]"){
				sortStr = params."sort[${sortIndex}][dir]"
				feildStr =  params."sort[${sortIndex}][field]"

				if("targetDate".equals(feildStr)){
					order("punchStartClockTime", "$sortStr")
					
				}else if("team".equals(feildStr)){
					applicant{
						group{
							order('name', "$sortStr")
						}
					}
				}else{
					order(feildStr, "$sortStr")
				}

				sortIndex++
			}
			//-------------------------------------排序 END

			order("punchStartClockTime", "desc")
			firstResult params.skip?.toInteger() ?: 0
			maxResults params.pageSize?.toInteger() ?: 100
		}

		def total = Overtime.withCriteria {
			projections{ count('id') }
			isNotNull('punchEndClockTime')

			// > '从日期'
			if(StringUtils.isNotBlank(params.qStartTime)){
				ge('punchStartClockTime',sf.parse(params.qStartTime))
			}

			// < '到日期' + 1
			if(StringUtils.isNotBlank(params.qEndTime)){
				Calendar cal = Calendar.getInstance();
				cal.setTime(sf.parse(params.qEndTime));
				cal.add(Calendar.DAY_OF_YEAR, 1)

				lt('punchStartClockTime',cal.getTime())
			}

			if(StringUtils.isNotBlank(params.userGroup)){
				applicant{
					group{
						eq('name', params.userGroup)
					}
				}
			}

		}[0]

		def workingHour=0
		def statusCauses=''
		def mealCnt=0

		render(contentType:"text/json"){
			[
				total:total,
				overtimes:array{

					overtimeList.each{

						if(it.punchEndClockTime && it.punchStartClockTime){
							workingHour = new BigDecimal((it.punchEndClockTime.getTime() - it.punchStartClockTime.getTime())/ (1000 * 60 * 60f)).setScale(1, BigDecimal.ROUND_HALF_UP)
						}else{
							workingHour=0
						}

						if(it.statusCauses){
							statusCauses = "(${it.statusCauses})"
						}else{
							statusCauses=''
						}

						def overtime = it
						mealCnt = OvertimeMeal.withCriteria {
							projections{ count('id') }
							eq('overtime',overtime)
						}[0]

						row(id: it.id,  project: it.project, reason:it.reason, type: it.type.label,
						status: it.status.label + statusCauses, team:it.applicant.group.name,
						punchStartClockTime: sftime.format(it.punchStartClockTime),
						punchEndClockTime: sftime.format(it.punchEndClockTime),
						workingHour:workingHour, mealCnt:mealCnt, createdBy: it.audited.createdBy)
					}
				}
			]
		}
	}
	// -----------------------------------------------------------------------------统计请求action
	def export(){
		String fileName = "加班统计_${params.qStartTime}_${params.qEndTime}_${params.group?:''}"
		fileName =  new String(fileName.getBytes("gb2312"), "ISO8859-1")
		response.setHeader("Content-disposition", "attachment; filename=${fileName}.xls")

		def out = response.outputStream

		def overtimeList = Overtime.withCriteria {
			isNotNull('punchEndClockTime')
			eq('status',OvertimeStatus.VALID)

			// > '从日期'
			if(StringUtils.isNotBlank(params.qStartTime)){
				ge('punchStartClockTime',sf.parse(params.qStartTime))
			}

			// < '到日期' + 1
			if(StringUtils.isNotBlank(params.qEndTime)){
				Calendar cal = Calendar.getInstance();
				cal.setTime(sf.parse(params.qEndTime));
				cal.add(Calendar.DAY_OF_YEAR, 1)

				lt('punchStartClockTime',cal.getTime())
			}

			if(StringUtils.isNotBlank(params.userGroup)){
				applicant{
					group{
						eq('name', params.userGroup)
					}
				}
			}

			//用加班人所属专项组排序
			applicant{
				group{ order("name", "asc") }
			}

		}

		def groupOvertimeMap = overtimeService.stastic(overtimeList)
		def wb = overtimeService.exportExcel(groupOvertimeMap)

		//写回文件内容
		wb.write(out)

		out.flush()
		out.close()
	}
}
